package cn.edu.ncut.cs.springboot.springsecuritydemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import java.io.PrintWriter;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    /**
     * 密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/index", "/home").permitAll() // 允许匿名访问
                        .requestMatchers("/user/**").hasRole("ADMIN") // 仅 ADMIN 角色可以访问
                        .requestMatchers("/user/view/**").hasRole("ADMIN") // 仅 ADMIN 角色可以访问
                        .requestMatchers("/user/list").hasAuthority("user:list") // 需要 user:list 权限
                        .requestMatchers("/verifycode").permitAll() // 允许匿名访问
                        .requestMatchers("/api/attendance").hasAnyRole( "NORMAL_USER","ADMIN","HR") // 允许三种权限访问
                        .requestMatchers("/api/attendance/{id}").hasAnyRole( "NORMAL_USER","ADMIN","HR") // 允许三种权限访问
                        .requestMatchers("/api/attendance/employee/{employeeId}").hasAnyRole( "NORMAL_USER","ADMIN","HR") // 允许三种权限访问
                        .requestMatchers("/api/attendance/manage/**").hasAnyRole( "ADMIN","HR")

                        .requestMatchers("/wode/system/**").hasRole("ADMIN") // 仅 ADMIN 角色可以访问
                        .requestMatchers("/usercreate/**").hasRole("ADMIN") // 仅 ADMIN 角色可以访问
                        .requestMatchers("/permissions").permitAll()
                        .requestMatchers("/permissions/{*}").permitAll()
                        .anyRequest().authenticated() // 其他请求需要认证
                )
                .httpBasic(withDefaults()) // 启用 Basic Auth
                .formLogin(withDefaults()) // 启用表单登录
                .logout(logout -> logout
                        .logoutUrl("/logout")
                        .logoutSuccessHandler((req, resp, authentication) -> {
                            resp.setContentType("application/json;charset=utf-8");
                            PrintWriter out = resp.getWriter();
                            out.write("{\"message\":\"logout success\"}");
                            out.flush();
                        })
                        .permitAll()
                )
                .csrf(AbstractHttpConfigurer::disable); // 禁用 CSRF

        return http.build();
    }
}